const { protocol } = require('electron')
const path = require('path')
const { readFile } = require('fs')
const { URL } = require('url');

/**
 * 
 *  注意：在app协议下  页面打开devToos会触发一个/work/offline-client/dist/，readFile无法读取目录，所以会报错。
    Failed to read /work/offline-client/dist/ on app protocol [Error: EISDIR: illegal operation on a directory, read] {
      errno: -4068,
      code: 'EISDIR',
      syscall: 'read'
    }
 */


let createProtocol = (scheme) => {
  protocol.registerBufferProtocol(
    scheme,
    (request, respond) => {
      let pathName = new URL(request.url).pathname
      pathName = decodeURI(pathName)
      readFile(pathName, (error, data) => {
        if (error) {
          console.error(
            `Failed to read ${pathName} on ${scheme} protocol`,
            error
          )
        }
        const extension = path.extname(pathName).toLowerCase()
        let mimeType = ''
        if (extension === '.js') {
          mimeType = 'text/javascript'
        } else if (extension === '.html') {
          mimeType = 'text/html'
        } else if (extension === '.css') {
          mimeType = 'text/css'
        } else if (extension === '.svg' || extension === '.svgz') {
          mimeType = 'image/svg+xml'
        } else if (extension === '.json') {
          mimeType = 'application/json'
        } else if (extension === '.wasm') {
          mimeType = 'application/wasm'
        }
        respond({
          mimeType,
          data
        })
      })
    }
  )
}

export {
  createProtocol
}